# -*- coding: utf-8 -*-
import urllib2
import cookielib
import urllib
import json


def saveCookie(url,date):
    #设置保存cookie的文件
    filename = 'cookie.txt'
    #声明一个MozillaCookieJar对象来保存cookie，之后写入文件
    cookie = cookielib.MozillaCookieJar(filename)
    #创建cookie处理器
    handler = urllib2.HTTPCookieProcessor(cookie)
    #构建opener
    opener = urllib2.build_opener(handler)
    #创建请求
    res = opener.open(url,date)
    #保存cookie到文件
    #ignore_discard的意思是即使cookies将被丢弃也将它保存下来
    #ignore_expires的意思是如果在该文件中cookies已经存在，则覆盖原文件写入
    cookie.save(ignore_discard=True,ignore_expires=True)

#从文件中获取cookie并且访问(我们通过这个方法就可以打开保存在本地的cookie来模拟登录)
def getCookie():
    #创建一个MozillaCookieJar对象
    cookie = cookielib.MozillaCookieJar()
    #从文件中的读取cookie内容到变量
    cookie.load('cookie.txt',ignore_discard=True,ignore_expires=True)
    #打印cookie内容,证明获取cookie成功
    # for item in cookie:
    #     print 'name:' + item.name + '-value:' + item.value
    #利用获取到的cookie创建一个opener
    handler = urllib2.HTTPCookieProcessor(cookie)
    return urllib2.build_opener(handler)


def index():
    return dict(message='')

def lookview():
    date = request.post_vars['date']
    hour = request.post_vars['hour']
    minute = request.post_vars['minute']

    main_url = "http://m.beibeiyue.com"
    # 9555 多多老师
    # 定义登录地址
    login_url = main_url + '/s/login'
    # 定义登录所需要用的信息，如用户名、密码等，详见下图，使用urllib进行编码
    login_data = urllib.urlencode({
        'username': '18640248536',
        'password': "18640248536",
        'deviceType': '1',
        'deviceNumber': 861234567890123, })

    view_url = main_url + '/s/reserveHours'
    view_data = urllib.urlencode({
        'babyType': '1',
        'date': date,
        'storeId': '870', })
    # 获取cookie 首次不存在cookie文件异常
    try:
        opener = getCookie()
    except:
        saveCookie(login_url, login_data)
        opener = getCookie()
    responsea = opener.open(view_url, view_data).read()
    s = json.loads(responsea)

    # 如何失效重新登录
    if s['result'] != '0':
        saveCookie(login_url, login_data)
        opener = getCookie()
        print 'relogin'

    # 正常业务逻辑
    response2 = opener.open(view_url, view_data).read()


    reserveTeachers_url = main_url + '/s/reserveTeachers'
    reserveTeachers_data = urllib.urlencode({
        'babyType': '1',
        'date': date,
        'hour': hour,
        'minute': minute,
        'storeId': '870',
    })
    response1 = opener.open(reserveTeachers_url, reserveTeachers_data).read()


    datelist_nr = ''
    s = json.loads(response2)
    if s['result']=='0':
        for ev in s['data']['list']:
            datelist_nr=datelist_nr+'<li class="am-g am-list-item-desced">' \
                                    ''+('<span class="am-badge am-badge-success">YES</span>' if ev['flag']=='true' else '<span class="am-badge am-badge-danger">NO</span>')+'<a class="am-list-item-hd ">'+ev['hour']+':'+ev['minute']+'</a>' \
                                    '<div class="am-list-item-text">'+ev['info']+'</div></li>'
    else:
        datelist_nr = s['message']
    datelist='  <div data-am-widget="list_news" class="am-list-news am-list-news-default" ><div class="am-list-news-hd am-cf"><h2>'+date +u'预约情况'+'</h2></div><div class="am-list-news-bd"><ul class="am-list">'+datelist_nr+'</ul></div></div>'

    print response1
    datelist_nr1 = ''
    s = json.loads(response1)
    if s['result']=='0':
        for ev in s['data']['list']:
            datelist_nr1=datelist_nr1+'<li class="am-g am-list-item-desced">' \
                                    '<img src="'+ev['img']+'" ></img><a class="am-list-item-hd ">'+ev['id']+'--'+ev['name']+'</a>' \
                                    '<div class="am-list-item-text"></div></li>'
    else:
        datelist_nr1 = s['message']
    datelist1='  <div data-am-widget="list_news" class="am-list-news am-list-news-default" ><div class="am-list-news-hd am-cf"><h2>'+date+'  '+hour+':'+minute+u'预约情况'+'</h2></div><div class="am-list-news-bd"><ul class="am-list">'+datelist_nr1+'</ul></div></div>'

    print datelist1

    return response.json({'status': 'ok', 'msg': 'msg','data':datelist,'data1':datelist1})

def lookview_t():
    date = request.post_vars['date']
    hour = request.post_vars['hour']
    minute = request.post_vars['minute']
    id = request.post_vars['id']

    main_url = "http://m.beibeiyue.com"
    # 9555 多多老师
    # 定义登录地址
    login_url = main_url + '/s/login'
    # 定义登录所需要用的信息，如用户名、密码等，详见下图，使用urllib进行编码
    login_data = urllib.urlencode({
        'username': '18640248536',
        'password': "18640248536",
        'deviceType': '1',
        'deviceNumber': 861234567890123, })

    view_url = main_url + '/s/reserveHours'
    view_data = urllib.urlencode({
        'babyType': '1',
        'date': date,
        'storeId': '870', })
    # 获取cookie 首次不存在cookie文件异常
    try:
        opener = getCookie()
    except:
        saveCookie(login_url, login_data)
        opener = getCookie()
    responsea = opener.open(view_url, view_data).read()
    s = json.loads(responsea)

    # 如何失效重新登录
    if s['result'] != '0':
        saveCookie(login_url, login_data)
        opener = getCookie()
        print 'relogin'

    # 正常业务逻辑

    reserve_url = main_url + '/s/reserve'
    reserve_data = urllib.urlencode({
        'babyType': '1',
        'date': date,
        'hour': hour,
        'minute': minute,
        'teacher': id,
        'storeId': '870',
    })
    response1 = opener.open(reserve_url, reserve_data).read()
    return response.json({'status': 'ok', 'msg': 'msg','data':response1})
